#include <types.h>
#include <IO.h>
#include <IRQ.h>
#include <PIT.h>

qword PIT::Ticks;

void PIT::Init() {
	// 100 HZ
	word val = 1193180 / 100;
	outb(0x43, 0x36);
	outb(0x40, val & 0xFF);
	outb(0x40, val >> 8);

	IRQ::Register(0, (dword) &Handler);
	IRQ::Enable(0);
}

void PIT::StartSound(word freq) {
	word val = 1193180 / freq;
	outb(0x43, 0xB6);
	outb(0x42, val & 0xFF);
	outb(0x42, val >> 8);

	// Play
	byte tmp = inb(0x61);
	if (tmp != (tmp | 3)) {
		outb(0x61, tmp | 3);
	}
}

void PIT::StopSound() {
	outb(0x61, inb(0x61) & 0xFC);
}

void PIT::Sound(word freq, dword ms) {
	StartSound(freq);
	//Sleep(ms);
	StopSound();
}

void PIT::Handler(CPUContext *ctx) {
	Ticks++;
}
